#include <string>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>

using namespace std;

int
main (int argc, char *argv[])
{

	if (argc <= 1)
	{

		cout << "error: error of command line, the parament is not enough"
			<< endl;

		return -1;

	}

	bool aftervia = false;

	unsigned int countvia = 0;

	string tempcommand;

	string tempviafile_context;

	string viafile_context;

	fstream tempviafile;

	for (int i = 0; i < argc; i++)
	{

		if (strcmp (argv[i], "-via") == 0)
		{

			countvia++;

			aftervia = true;

		}

		else if (countvia > 0 && aftervia == true)
		{

			tempviafile.open (argv[i], fstream::in);

			if (tempviafile.is_open ())
			{

#ifdef __DEBUG__
				cout << "debug: via " << argv[i] << " file opend" << endl;
#endif

				while (!tempviafile.eof ())
				{
#ifdef __DEBUG__
					cout << "debug: read one line" << endl;
#endif

					getline (tempviafile, tempviafile_context);

					viafile_context.append (tempviafile_context);

					tempviafile_context.clear ();

				}

			}

			else
			{

				cout << "error: via file " << argv[i] <<
					" open failed, quit application" << endl;

				return -1;

			}

			tempviafile.close ();

			tempcommand.append (" ");

			tempcommand.append (viafile_context);

			aftervia = false;

		}

		else
		{

			tempcommand.append (argv[i]);

			tempcommand.append ("  ");

		}

	}

	if (countvia <= 0)
	{

		cout << "error: the parament did not contain -via flag" << endl;

		return -1;

	}
#ifdef __DEBUG__
	cout << "debug: parser stage 1 (with wrapper)" << endl << tempcommand
		<< endl;
#endif

	unsigned int first_flag = tempcommand.find ("  ");

	tempcommand.erase (0, first_flag);

#ifdef __DEBUG__
	cout << "debug: parser stage 2 (erase wrapper flag)" << endl <<
		tempcommand << endl;
#endif

	fstream filecpptest;

	filecpptest.open ("cpptest.cfg", fstream::in);
	string tmpcpptest;

	if (filecpptest.is_open ())
	{
		getline (filecpptest, tmpcpptest);
	}
	else
	{
		cout << "error: cpptest.cfg file open failed." << endl;
	}
	filecpptest.close ();

	tempcommand.insert (0, tmpcpptest);
	tempcommand.append ("\n\n");

#ifdef __DEBUG__
	cout << "debug: parser stage 3 (add cpptest to the beginning)" << endl
		<< tempcommand << endl;
#endif

	fstream out;

	out.open ("command.txt", fstream::out | fstream::app);
	out.write (tempcommand.c_str (), tempcommand.size ());
	out.flush ();
	out.close ();

#ifdef __DEBUG__
	system ("pause");
#endif

	return 0;

}
